#include "mysqldb.h"
#include "public.h"
#include "logger.h"

#include <string>
#include <sstream>
#include <iostream>

void MySQLDB::Connect(const std::string& ip, unsigned short port, const std::string& user, 
    const std::string& password, const std::string& db) {
    
    m_mysqlClient = mysql_init(nullptr);
    if ( !mysql_real_connect(m_mysqlClient, ip.c_str(), user.c_str(), password.c_str(), db.c_str(), 3306, nullptr, 0) ) {
        LOG_ERROR << "mysql_real_connect() failed!";
    }
    LOG_INFO << "mysql connect success!";
}

//查询
int MySQLDB::Query(std::string&& sql) {
    // return value
    LOG_INFO << "sql:" << sql;

    // 执行成功返回0
    if (mysql_query(m_mysqlClient, sql.c_str())) {
        LOG_ERROR <<  mysql_error(m_mysqlClient);
        return 0;
    }

    return mysql_num_rows(mysql_store_result(m_mysqlClient));
}

//插入
bool MySQLDB::Insert(std::string&& sql) {
    // return value
    LOG_INFO << "sql:" << sql;
    
    // 执行成功返回0
    if (mysql_query(m_mysqlClient, sql.c_str())) {
        LOG_ERROR <<  mysql_error(m_mysqlClient);
        return false;
    }

    return true;
}

MySQLDB::~MySQLDB() {
    if (m_mysqlClient != nullptr) {
        mysql_close(m_mysqlClient);
    }
}